package com.leonardo.persistenceme;

import java.util.Hashtable;
import java.util.Vector;

import com.leonardo.persistenceme.exceptions.AlreadyPersistedException;
import com.leonardo.persistenceme.model.Entity;


public class PersistGraphController {

	private static Hashtable recoveringEntities = new Hashtable();
	private static Vector persistingEntities = new Vector();
	private static int nextKey;
	private static int persisting = 0;
	private static int recovering = 0;
	
	public static void addEntity(Entity entity, int nextPossibleKey) throws AlreadyPersistedException {
		persisting++;
		if(persistingEntities.contains(entity))
			throw new AlreadyPersistedException();
		persistingEntities.addElement(entity);
		if(persisting == 1)
			nextKey = nextPossibleKey;
		if(entity.getKey() == null)
			entity.setKey(nextKey());
	}
	
	private static Integer nextKey() {
		Integer next = new Integer(nextKey);
		nextKey++;
		return next;
	}
	
	public static boolean endEntity() {
		persisting--;
		if(persisting == 0) {
			persistingEntities.removeAllElements();
			return true;
		}
		return false;
	}
	
	public static int maxKey() {
		return nextKey;
	}
	
	public static void addRecovered(Entity entity) {
		recoveringEntities.put(entity.getKey(), entity);
		recovering++;
	}
	
	public static void endRecover() {
		recovering--;
		if(recovering == 0)
			recoveringEntities.clear();
	}
	
	public static Entity alreadyRecovered(Integer key) {
		if(recoveringEntities.containsKey(key))
			return (Entity) recoveringEntities.get(key);
		return null;
	}
}
